package com.hava.mybatis.user.service;

import com.hava.mybatis.user.entity.GetUserInfo;
import com.hava.mybatis.user.entity.User;
import com.hava.mybatis.user.repository.GetUserInfoAnnotation;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * Created by zhanpeng on 09/10/2016.
 */
public class HelloMyBatis {

    public static void main(String [] args)
    {
        //1.声明MyBatis的配置文件目录
        String resource = "mybatis-conf.xml";

        //2.加载应用程序配置文件
        InputStream inputStream = HelloMyBatis.class.getClassLoader().getResourceAsStream(resource);

        //3.创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        Configuration configuration = sqlSessionFactory.getConfiguration();

        //Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface com.hava.mybatis.user.entity.GetUserInfo is already known to the MapperRegistry.
        configuration.addMapper(GetUserInfoAnnotation.class);

        //4.获取Session
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            //5.获取操作类
//            GetUserInfo getUserInfo = sqlSession.getMapper(GetUserInfo.class);
            //使用注解的方式
            GetUserInfoAnnotation getUserInfo = sqlSession.getMapper(GetUserInfoAnnotation.class);
            //6.完成查询操作
            User user = getUserInfo.getUser(1);
            System.out.println("[user.getUserName]:" + user.getUserName());

        }
        finally {
            //7.关闭session
            sqlSession.close();
        }

    }
}
